package com.forum.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.forum.bean.Follows;
import com.forum.common.Result;
import com.forum.dto.FollowListDto;
import com.forum.dto.FollowRequest;
import com.forum.mapper.FollowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FollowService {
    @Autowired
    private FollowMapper followMapper;

    /**
     * 关注用户
     * 逻辑：
     * 1. 先查询是否已经关注，防止重复插入；
     * 2. 若尚未关注，则插入关注记录；
     * 3. 返回成功信息。
     */
    @Transactional
    public Result<String> follow(FollowRequest request) {
        try {
            // 检查是否已存在关注记录
            QueryWrapper<Follows> query = new QueryWrapper<>();
            query.eq("follower_id", request.getFollowerId())
                    .eq("followed_id", request.getFollowingId());
            Follows exist = followMapper.selectOne(query);
            if (exist != null) {
                return Result.fail("已关注该用户");
            }
            // 构建关注记录并插入
            Follows follow = new Follows();
            follow.setFollowerId(request.getFollowerId());
            follow.setFollowedId(request.getFollowingId());
            int rows = followMapper.insert(follow);
            if (rows != 1) {
                return Result.fail("关注失败");
            }
            return Result.ok("关注成功");
        } catch (Exception e) {
            return Result.fail("关注异常：" + e.getMessage());
        }
    }

    /**
     * 取消关注用户
     * 逻辑：
     * 1. 查询是否存在关注记录，若存在则删除；
     * 2. 返回操作结果。
     */
    @Transactional
    public Result<String> unfollow(FollowRequest request) {
        try {
            QueryWrapper<Follows> query = new QueryWrapper<>();
            query.eq("follower_id", request.getFollowerId())
                    .eq("followed_id", request.getFollowingId());
            Follows exist = followMapper.selectOne(query);
            if (exist == null) {
                return Result.fail("尚未关注该用户");
            }
            int rows = followMapper.delete(query);
            if (rows != 1) {
                return Result.fail("取消关注失败");
            }
            return Result.ok("取消关注成功");
        } catch (Exception e) {
            return Result.fail("取消关注异常：" + e.getMessage());
        }
    }


    public Result<List<Integer>> getFollowList(Integer queryUserId) {
        try{
            Follows f = new Follows();
            f.setFollowerId(queryUserId);
            List<Follows> fs = followMapper.selectList(new QueryWrapper<>(f));
            List<Integer> ids = fs.stream()
                    .map(Follows::getFollowedId)
                    .collect(Collectors.toList());
            return Result.ok(ids);
        }catch (Exception e){
            return Result.fail("查询关注列表异常：" + e.getMessage());
        }
    }


    /**
     * 查询关注列表
     * @param queryUserId 查询的用户ID（即该用户的关注列表）
     * @param currentUserId 当前登录用户ID，用于判断当前用户是否关注返回结果中的用户
     * @return 结果集合
     */
    public Result<List<FollowListDto>> getFollowList(Integer queryUserId, Integer currentUserId) {
        try {
            List<FollowListDto> list = followMapper.selectFollowList(queryUserId, currentUserId);
            return Result.ok(list);
        } catch (Exception e) {
            return Result.fail("查询关注列表异常：" + e.getMessage());
        }
    }
}
